/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package testing.jee.util;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

/**
 *
 * @author kreisera
 */
public class DateUtils {
    
    private static final Calendar cal = GregorianCalendar.getInstance(TimeZone.getTimeZone("UTC"));
    
    /**
     * Sets the time back to 00:00:0000 UTC of the given day.
     * 
     * @param date Date to normalize
     * @return Normalized date
     */
    public static synchronized Date normalize(Date date) {
        cal.setTime(date);
        cal.set(Calendar.MILLISECOND, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        return cal.getTime();
    }
    
    /**
     * Sets the time back to 00:00:0000 UTC and the day of the week (MO-FR) to the given day.
     * 
     * @param date Date to normalize
     * @param dayOfWeek Day of week 
     * @return Normalized date
     */
    public static synchronized Date normalize(Date date, int dayOfWeek) {
        cal.setTime(date);
        cal.set(Calendar.MILLISECOND, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.DAY_OF_WEEK, dayOfWeek);
        return cal.getTime();
    }
    
    public static synchronized Date toEndOfWeek(Date date) {
        cal.setTime(date);
        cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
        return cal.getTime();
    }
    
    public static synchronized Date toStartOfWeek(Date date) {
        cal.setTime(date);
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        return cal.getTime();
    }
    
    public static synchronized Date toNextWeek(Date date) {
        cal.setTime(date);
        cal.add(Calendar.WEEK_OF_YEAR, 1);
        return cal.getTime();
    }
    
    public static synchronized Date toPreviousWeek(Date date) {
        cal.setTime(date);
        cal.add(Calendar.WEEK_OF_YEAR, -1);
        return cal.getTime();
    }
    
    public static synchronized Date toNextWorkDay(Date date) {
        cal.setTime(date);
        if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY)
            cal.add(Calendar.DAY_OF_YEAR, 3);
        else if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY)
            cal.add(Calendar.DAY_OF_YEAR, 2);
        else
            cal.add(Calendar.DAY_OF_YEAR, 1);
        return cal.getTime();
    }
}
